package android.activities;

import data.databases.MySQL;
import data.databases.RequestMethod;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;

public class InitActivity extends Activity implements Runnable {

	private ProgressDialog _pd;
	private boolean _isNewUser = true;
	private String _uuid;
	private MySQL _sqlClient;
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.init);
		
		_sqlClient = new MySQL();
		
		/*TelephonyManager telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		_uuid = telManager.getDeviceId();*/
		_uuid = "123000456000789";
		
		_pd = ProgressDialog.show(this, "", "Controleren parkeerplaatsen. Even geduld a.u.b.", true, false);
		Thread thread = new Thread(this);
		thread.start();
	}
	
	@Override
	public void run() {
		if(isExistingUser(_uuid)) 
			_isNewUser = false; 
		else 
			_isNewUser = true; 	
		
		handler.sendEmptyMessage(0);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			_pd.dismiss();
			
			Intent intent;
			
			if(_isNewUser == true) {
				try {
					intent = new Intent(InitActivity.this, AddParkingActivity.class);
					InitActivity.this.startActivity(intent);
				}
				catch (Exception ex) { Log.e("ERROR", "Error: " + ex.toString()); }
			}
			else if(_isNewUser == false) {
				try {
					intent = new Intent(InitActivity.this, ShowParkingActivity.class);
					InitActivity.this.startActivity(intent);
				}
				catch (Exception ex) { Log.e("ERROR", "Error: " + ex.toString()); }
			}
		}
	};
	
	public boolean isExistingUser(String uuid) {
		_sqlClient.AddParam("hardwareid", uuid);
		//_sqlClient.AddHeaders("Content-Type", "application/json");
		
		try {
			_sqlClient.Execute(RequestMethod.GET, "getUserParkingSpace.php");
		} 
		catch (Exception ex ) { Log.e("ERROR", "MySQL Error: " + ex.toString()); }
		
		String result = _sqlClient.getResponse();
		if(result != null) {
			Log.i("result", result); // show result in log.(testing purposes only)
			return true;
		}	
		else { Log.e("ERROR", "Error: Result is null -> " + result); }
		
		return false;
	}
}
